<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="profile-header">
            <div class="avatar-container">
              <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar"></el-avatar>
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <el-button size="small" type="text">更换头像</el-button>
              </el-upload>
            </div>
            <h2 class="username">{{ userInfo.username }}</h2>
            <p class="email">{{ userInfo.email }}</p>
            <el-tag :type="userInfo.role === 'ADMIN' ? 'danger' : 'primary'">
              {{ userInfo.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </div>
          <div class="profile-info">
            <p><i class="el-icon-date"></i> 注册时间：{{ formatDate(userInfo.createTime) }}</p>
            <p><i class="el-icon-time"></i> 最后登录：{{ formatDate(userInfo.lastLoginTime) }}</p>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-card>
          <div slot="header" class="header">
            <span>个人信息</span>
            <el-button type="primary" @click="handleEdit">编辑信息</el-button>
          </div>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ userInfo.phone || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ userInfo.gender === '男' ? '男' : userInfo.gender === '女' ? '女' : '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="生日">{{ userInfo.birthday || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{ userInfo.address || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="个人简介" :span="2">{{ userInfo.bio || '这个人很懒，什么都没写~' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <el-card class="security-card">
          <div slot="header" class="header">
            <span>安全设置</span>
          </div>
          
          <el-row class="security-item">
            <el-col :span="18">
              <h4>账户密码</h4>
              <p>建议您定期更换密码，设置一个包含字母、数字和特殊字符的密码会更安全</p>
            </el-col>
            <el-col :span="6" class="security-action">
              <el-button type="text" @click="showPasswordDialog">修改密码</el-button>
            </el-col>
          </el-row>
          
          <el-row class="security-item">
            <el-col :span="18">
              <h4>绑定手机</h4>
              <p>已绑定手机：{{ maskPhone(userInfo.phone) || '未绑定' }}</p>
            </el-col>
            <el-col :span="6" class="security-action">
              <el-button type="text" @click="showPhoneDialog">{{ userInfo.phone ? '更换手机' : '绑定手机' }}</el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 编辑个人信息对话框 -->
    <el-dialog title="编辑个人信息" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address"></el-input>
        </el-form-item>
        <el-form-item label="个人简介" prop="bio">
          <el-input type="textarea" v-model="editForm.bio" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input type="password" v-model="passwordForm.oldPassword"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="passwordForm.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="passwordForm.confirmPassword"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPasswordForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 绑定手机对话框 -->
    <el-dialog :title="userInfo.phone ? '更换手机' : '绑定手机'" :visible.sync="phoneDialogVisible" width="400px">
      <el-form :model="phoneForm" :rules="phoneRules" ref="phoneForm" label-width="100px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="phoneForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="phoneForm.code">
            <el-button slot="append" @click="sendCode" :disabled="codeSending">
              {{ codeSending ? `${countdown}s后重试` : '获取验证码' }}
            </el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="phoneDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPhoneForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'Profile',
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      userInfo: {},
      editDialogVisible: false,
      passwordDialogVisible: false,
      phoneDialogVisible: false,
      editForm: {
        username: '',
        email: '',
        phone: '',
        gender: '',
        birthday: '',
        address: '',
        bio: ''
      },
      editRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      phoneForm: {
        phone: '',
        code: ''
      },
      phoneRules: {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
        ]
      },
      codeSending: false,
      countdown: 60
    }
  },
  computed: {
    ...mapGetters(['currentUser'])
  },
  created() {
    this.fetchUserInfo()
  },
  methods: {
    async fetchUserInfo() {
      try {
        const response = await this.$http.get('/user/profile', {
          headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
          }
        })
        if (response.data.code === 20000) {
          this.userInfo = response.data.data
        } else {
          this.$message.error(response.data.message || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.$message.error('获取用户信息失败')
      }
    },
    formatDate(date) {
      if (!date) return '未知'
      return new Date(date).toLocaleString()
    },
    maskPhone(phone) {
      if (!phone) return ''
      return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
    },
    handleEdit() {
      this.editForm = { ...this.userInfo }
      this.editDialogVisible = true
    },
    submitEditForm() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          try {
            await this.$http.put('/user/profile', this.editForm)
            this.$message.success('保存成功')
            this.editDialogVisible = false
            this.fetchUserInfo()
          } catch (error) {
            this.$message.error('保存失败')
          }
        }
      })
    },
    showPasswordDialog() {
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      this.passwordDialogVisible = true
    },
    submitPasswordForm() {
      this.$refs.passwordForm.validate(async valid => {
        if (valid) {
          try {
            await this.$http.put('/user/password', {
              oldPassword: this.passwordForm.oldPassword,
              newPassword: this.passwordForm.newPassword
            })
            this.$message.success('密码修改成功')
            this.passwordDialogVisible = false
          } catch (error) {
            this.$message.error(error.response?.data?.message || '密码修改失败')
          }
        }
      })
    },
    showPhoneDialog() {
      this.phoneForm = {
        phone: '',
        code: ''
      }
      this.phoneDialogVisible = true
    },
    async sendCode() {
      if (!this.phoneForm.phone) {
        this.$message.warning('请先输入手机号码')
        return
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.phoneForm.phone)) {
        this.$message.warning('请输入正确的手机号码')
        return
      }
      
      this.codeSending = true
      try {
        await this.$http.post('/user/send-code', { phone: this.phoneForm.phone })
        this.$message.success('验证码已发送')
        this.startCountdown()
      } catch (error) {
        this.$message.error('验证码发送失败')
        this.codeSending = false
      }
    },
    startCountdown() {
      this.countdown = 60
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
          this.codeSending = false
        }
      }, 1000)
    },
    submitPhoneForm() {
      this.$refs.phoneForm.validate(async valid => {
        if (valid) {
          try {
            await this.$http.put('/user/phone', this.phoneForm)
            this.$message.success('手机绑定成功')
            this.phoneDialogVisible = false
            this.fetchUserInfo()
          } catch (error) {
            this.$message.error('手机绑定失败')
          }
        }
      })
    },
    handleAvatarSuccess(res) {
      this.userInfo.avatar = res.data
      this.$message.success('头像上传成功')
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  text-align: center;
}

.profile-header {
  padding: 20px 0;
}

.avatar-container {
  margin-bottom: 20px;
}

.username {
  margin: 10px 0;
  font-size: 20px;
}

.email {
  color: #909399;
  margin-bottom: 10px;
}

.profile-info {
  text-align: left;
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

.profile-info p {
  margin: 10px 0;
  color: #606266;
}

.profile-info i {
  margin-right: 5px;
  color: #409EFF;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-card {
  margin-top: 20px;
}

.security-item {
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.security-item:last-child {
  border-bottom: none;
}

.security-item h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
}

.security-item p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.security-action {
  text-align: right;
  line-height: 60px;
}
</style> 